<template>
  <div class="quantity_detail_content">
    <div class="head">
      <div class="title">
        <div class="title_round"></div>
        <div>{{ detailInfo.budgetName }}</div>
      </div>
      <div class="suffix">
        <div class="rate_text" v-if="detailInfo.showGrossProfit === 1">
          <div class="tip">
            <img src="@/assets/images/tip.png" />
          </div>
          当前订单毛利润：
          <div class="rate">{{ `${detailInfo.grossProfitRate}%` }}</div>
        </div>
        <div class="rate_text" v-if="detailInfo.showGrossProfitLimit === 1">
          订单毛利润限制：
          <div class="rate">{{ `${detailInfo.limitGrossProfitRate}%` }}</div>
        </div>
      </div>
    </div>
    <div class="content">
      <div class="anchor">
        <el-anchor :container="tableList">
          <el-anchor-link class="first_link" href="#space">
            {{ `空间（${detailInfo.spaceList.length}）` }}
            <template #sub-link>
              <el-anchor-link
                class="second_link"
                v-for="item in detailInfo.spaceList"
                :key="item.spaceId"
                :href="`#anchor${item.spaceId}`"
              >
                {{ item.spaceName }}
              </el-anchor-link>
            </template>
          </el-anchor-link>
          <el-anchor-link class="first_link" :href="`#comprehensive`">
            {{ `综合项（${detailInfo.comprehensiveList.length}）` }}
          </el-anchor-link>
          <el-anchor-link class="first_link" :href="`#summary`"> 预算汇总 </el-anchor-link>
        </el-anchor>
      </div>
      <div ref="tableList" class="table_list">
        <div class="space" v-for="item in detailInfo.spaceList" :id="`anchor${item.spaceId}`" :key="item.spaceId">
          <div>
            <div class="title">
              <div class="title_left">
                <div class="name">{{ item.spaceName || "--" }}</div>
                <div class="zone">
                  <span>（合计：</span>
                  <span class="high_light">¥{{ item.spaceTotalMoney || "--" }} / </span>
                  <span>
                    {{
                      `面积：${item.area || "--"}㎡ 
                      长：${item.length || "--"}m 
                      宽：${item.width || "--"}m 
                      高：${item.height || "--"}m）`
                    }}
                  </span>
                </div>
              </div>

              <div class="action">
                <div class="material" @click="handleOpenModal(item, true)">
                  <div>材料</div>
                  <img src="@/assets/images/add_material.png" />
                </div>
                <div class="split_line"></div>
                <div class="quota" @click="handleOpenModal(item, false)">
                  <div>定额</div>
                  <img src="@/assets/images/add_material.png" />
                </div>
              </div>
            </div>
            <div class="table">
              <el-table
                border
                :data="item.quotaItemList"
                style="width: 100%"
                header-cell-class-name="table_head"
                :span-method="temp => tableArraySpan(item.quotaItemList, temp)"
              >
                <el-table-column type="index" label="序号" fixed="left" width="60" />
                <el-table-column prop="mainPicUrl" label="图片" fixed="left" width="120">
                  <template #default="{ row }">
                    <img v-if="row.mainPicUrl" class="row_img" :src="row.mainPicUrl" />
                    <span v-else>--</span>
                  </template>
                </el-table-column>
                <el-table-column prop="productName" label="商品名称" width="240" />
                <el-table-column prop="brandName" label="品牌" width="90" />
                <el-table-column prop="modeCode" label="型号" width="60" />
                <el-table-column prop="col3" label="单位" width="60" />
                <el-table-column prop="num" label="数量" width="60" />
                <el-table-column prop="actualUsedNum" label="实际施工用量" width="110">
                  <template #default="{ row }">
                    <el-input v-model="row.actualUsedNum" @blur="handleChangeActual(row)" />
                  </template>
                </el-table-column>
                <el-table-column prop="lostRate" label="耗损率" width="90" />
                <el-table-column v-if="detailInfo.showCost === 1" prop="costUnitPrice" label="成本单价" width="110" />
                <el-table-column prop="productUnitPrice" label="材料单价" width="110" />
                <el-table-column prop="workerUnitPrice" label="人工费单价" width="110" />
                <el-table-column prop="unitTotalMoney" label="单项合计" width="110" />
                <el-table-column prop="projectVal" label="预算工程量" width="110">
                  <template #default="{ row }">
                    <el-input v-if="row.isNuclear === 1" v-model="row.projectVal" @blur="handleChangeProject(row)" />
                    <span v-else>{{ row.projectVal }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="projectTotalMoney" label="汇总合计" width="110" />
                <el-table-column prop="quotaName" label="工程项目名称" width="110" />
                <el-table-column prop="standardDesc" label="材料及工艺说明" width="130" />
                <el-table-column prop="remark" label="备注" width="110">
                  <template #default="{ row }">
                    <span v-html="row.remark"></span>
                  </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="60">
                  <template #default="{ row }">
                    <span v-if="row.isNuclear === 1">
                      <el-popconfirm title="确定要删除该项记录吗？" @confirm="handleDelete(row.contentId)">
                        <template #reference>
                          <el-button link type="primary">删除</el-button>
                        </template>
                      </el-popconfirm>
                    </span>
                    <span v-else></span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="memo">
              <div>备注说明</div>
              <div class="table_remark" v-html="item.remark" />
            </div>
          </div>
        </div>
        <div class="space">
          <div id="comprehensive">
            <div class="title">
              <div class="title_left">
                <div class="name">综合项</div>
                <div class="zone">
                  （合计：
                  <span class="high_light">¥{{ detailInfo.comprehensiveTotal }}</span>
                  ）
                </div>
              </div>
            </div>
            <div class="table">
              <el-table :data="detailInfo.comprehensiveList" stripe style="width: 100%" header-cell-class-name="table_head">
                <el-table-column type="index" label="序号" fixed="left" width="80" />
                <el-table-column prop="itemName" label="项目名称" fixed="left" />
                <el-table-column prop="moneyType" label="属性">
                  <template #default="{ row }">{{ getName("shop_budget_money_type", row.moneyType) }}</template>
                </el-table-column>
                <el-table-column prop="unit" label="单位" width="100">
                  <template #default="{ row }">{{ row.unit || "元" }}</template>
                </el-table-column>
                <el-table-column prop="linkTypesDesc" label="关联报价" />
                <el-table-column prop="feeRate" label="单价/比例" />
                <el-table-column prop="remark" label="说明备注" />
              </el-table>
            </div>
            <div class="tax">
              <div class="tax_box">
                <div class="tax_title">
                  <div class="tip">
                    <img src="@/assets/images/tip.png" />
                  </div>
                  <div>管理费</div>
                </div>
                <div class="tax_input">
                  <span>比例</span>
                  <el-input disabled style="width: 140px" v-model="detailInfo.managerFeeRate">
                    <template #suffix>%</template>
                  </el-input>
                </div>
              </div>
              <div class="tax_box">
                <div class="tax_title">
                  <div class="tip">
                    <img src="@/assets/images/tip.png" />
                  </div>
                  <div>税金费用</div>
                </div>
                <div class="tax_input">
                  <span>比例</span>
                  <el-input disabled style="width: 140px" v-model="detailInfo.taxesRate">
                    <template #suffix>%</template>
                  </el-input>
                </div>
              </div>
            </div>
          </div>
          <div id="summary">
            <div class="title">
              <div class="title_left">
                <div class="name">预算汇总表</div>
              </div>
            </div>
            <div class="table">
              <el-table :data="detailInfo.budgetSummary.itemList" stripe style="width: 100%" header-cell-class-name="table_head">
                <el-table-column type="index" label="序号" fixed="left" width="60" />
                <el-table-column prop="itemName" label="类别名称" fixed="left" />
                <el-table-column prop="itemDesc" label="计算明细" />
                <el-table-column prop="amount" label="价格" />
              </el-table>
            </div>
            <div class="memo">
              <div>备注说明</div>
              <div class="table_remark" v-html="detailInfo.budgetSummary.remark" />
            </div>
          </div>
        </div>
        <div class="affix">
          <el-affix position="bottom" :offset="20" style="width: 100%">
            <div class="affix_content">
              <div class="transaction">
                <div class="amount">
                  成交金额：<span class="amount_num">{{ `￥${detailInfo.concludeMoney}` }}</span>
                </div>
                <div class="memo">备注：{{ detailInfo.concludeRemark }}</div>
              </div>
              <div class="total">
                <div v-if="detailInfo.budgetType === 1">
                  <span class="total_text">合计总造价：</span>
                  <span class="total_num"> ¥{{ detailInfo.budgetTotlalMoney }} </span>
                  <span class="total_brackets">
                    （
                    <span class="total_detail">
                      {{
                        `房屋总面积：${detailInfo.houseArea}㎡ 
                      / 空间：${detailInfo.spaceItemNum}个 
                      / 综合项：${detailInfo.comprehensiveNum}个 
                      / 报价项：${detailInfo.budgetItemNum}项`
                      }}
                    </span>
                    ）
                  </span>
                </div>
                <div v-else>
                  <span class="total_text">套餐合计：</span>
                  <span class="total_num"> ¥{{ detailInfo.budgetTotlalMoney }} </span>
                  <span class="total_brackets">
                    {{
                      `（套餐价：¥${detailInfo.packageUnitPrice}/㎡
                      可享受：${detailInfo.packageSquareNum}/㎡
                      当前平方：${detailInfo.houseArea}㎡
                      每多出1平方：¥${detailInfo.packageOverUnitPrice}/㎡计算）`
                    }}
                  </span>
                  <div style="margin-top: 10px">
                    <span class="total_detail">
                      {{
                        `超出${detailInfo.overSquareNum}㎡：
                        ¥${detailInfo.overSquareNumMoney} 
                        + 个性化增项/配：¥${detailInfo.customIncreaseMoney} 
                        + 管理费：¥${detailInfo.manageFee} 
                        + 税金费：¥${detailInfo.taxesFee}`
                      }}
                    </span>
                  </div>
                </div>
                <div>
                  <el-button type="primary" @click="handleSubmit">核量完成并提交</el-button>
                </div>
              </div>
            </div>
          </el-affix>
        </div>
      </div>
    </div>
  </div>
  <commodityView
    ref="commodityViewRef"
    :show="materialFlag"
    :width="'1200px'"
    @close="materialFlag = false"
    @submit="handelSubmitImport"
  ></commodityView>

  <elDrawerView :show="quotaFlag" :title="'选择定额模版'" :size="'80%'" @close="quotaFlag = false">
    <impoQrtuota @getList="item => (quotaIportList = item)"></impoQrtuota>
    <div class="quota_btn">
      <el-button type="" @click="handelSaveQuota">取消</el-button>
      <el-button type="primary" @click="handelQuotaSubmit">已选中:{{ quotaIportList.length }}</el-button>
    </div>
  </elDrawerView>
</template>
<script setup>
import { ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import impoQrtuota from "@/views/budgetManagement/components/ImpoQrtuota/index.vue";
import commodityView from "@/views/budgetManagement/components/ImportMaterials/commodityView.vue";
import elDrawerView from "@/views/budgetManagement/components/elDrawerView";
import useCodeArrStore from "@/store/modules/select";
import { ElMessage } from "element-plus";
import {
  getQuantityDetail,
  packageAddQuota,
  packageAddMaterial,
  inventoryAddQuota,
  inventoryAddMaterial,
  updateActualUsedNum,
  updateProjectVal,
  deleteQuota,
  budgetCommit
} from "@/apis/budgetQuotation";

const getName = (dictType, code) => useCodeArrStore().getDictName(dictType, code);

const route = useRoute();
const router = useRouter();
const tableList = ref();
const currentSpace = ref("");
const materialFlag = ref(false);
const quotaFlag = ref(false);
const quotaIportList = ref([]);

const detailInfo = ref({
  spaceList: [],
  comprehensiveList: [],
  budgetSummary: {
    itemList: []
  }
});

const getDetailInfo = async id => {
  console.log(id);
  let { data } = await getQuantityDetail(id);
  detailInfo.value = data;
};

const handleOpenModal = (item, isMaterial) => {
  currentSpace.value = item.spaceId;
  if (isMaterial) materialFlag.value = true;
  else quotaFlag.value = true;
};

const handelSubmitImport = async list => {
  let apiFun;
  detailInfo.value.budgetType === 1 && (apiFun = inventoryAddMaterial);
  detailInfo.value.budgetType === 2 && (apiFun = packageAddMaterial);

  let { code } = await apiFun({
    skuIds: list.map(item => item.businessSkuId),
    spaceId: currentSpace.value,
    budgetId: detailInfo.value.budgetId
  });
  code === 200 && handleSuccess("材料添加成功");
  materialFlag.value = false;
};

const handelQuotaSubmit = async () => {
  let apiFun;
  detailInfo.value.budgetType === 1 && (apiFun = inventoryAddQuota);
  detailInfo.value.budgetType === 2 && (apiFun = packageAddQuota);

  let { code } = await apiFun({
    quotaIds: quotaIportList.value.map(item => item.quotaId),
    spaceId: currentSpace.value,
    budgetId: detailInfo.value.budgetId
  });
  code === 200 && handleSuccess("定额添加成功");
  quotaFlag.value = false;
};

const handleChangeActual = async row => {
  let { code } = await updateActualUsedNum({
    id: row.id,
    type: row.type,
    actualUsedNum: row.actualUsedNum
  });
  code === 200 && handleSuccess("修改成功");
};

const handleChangeProject = async row => {
  let { code } = await updateProjectVal({
    contentId: row.contentId,
    projectVal: row.projectVal
  });
  code === 200 && handleSuccess("修改成功");
};

const handleDelete = async contentId => {
  let { code } = await deleteQuota({ contentId });
  code === 200 && handleSuccess("删除成功");
};

const handleSubmit = async () => {
  let code = await budgetCommit({ nuclearId: detailInfo.value.nuclearId });
  code === 200 && handleSuccess("核量提交成功");
  router.back();
};

const handleSuccess = (message, type = "success") => {
  ElMessage({ type, message });
  getDetailInfo(route.query.contractId);
};

let contentIdList = [];
const tableArraySpan = (table, { row, columnIndex }) => {
  if (!table) return;

  if ([13, 14, 15, 16, 17, 18].indexOf(columnIndex) > -1) {
    if (!row.contentId) return;
    if (contentIdList[columnIndex] === row.contentId) return [0, 1];
    else contentIdList[columnIndex] = row.contentId;
    const rows = table.filter(item => {
      return item.contentId === contentIdList[columnIndex];
    });
    const count = rows.length;
    if (count > 1) {
      return [count, 1];
    }
  }
};

(() => {
  getDetailInfo(route.query.contractId);
})();
</script>
<style lang="scss">
.quantity_detail_content {
  height: 100%;

  .head {
    width: 100%;
    height: 60px;
    border-bottom: 1px solid #c2d4e8;
    padding: 5px 20px 0;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .title {
      display: flex;
      align-items: center;
      font-size: 18px;
      color: #131414;
      font-weight: 700;
      .title_round {
        width: 6px;
        height: 6px;
        border-radius: 50%;
        background: #409eff;
        margin-right: 11px;
      }
    }
    .suffix {
      display: flex;
      gap: 40px;
      line-height: 24px;
      .rate_text {
        display: flex;
        color: #3d3d3d;
        text-align: right;
        .tip {
          margin-right: 10px;
        }
      }
      .rate {
        font-weight: 700;
        color: #1a1a1a;
      }
    }
  }
  .content {
    display: grid;
    grid-template-columns: 200px calc(100% - 200px);
    height: calc(100% - 60px);
    .anchor {
      border-right: 1px solid #c2d4e8;
      padding: 10px 0px;
      .el-anchor__list {
        padding: 0;
      }
      .el-anchor__marker {
        opacity: 0 !important;
      }
      .first_link {
        .el-anchor__link {
          padding: 6px 20px;
          font-weight: 700;
          font-size: 14px;
          color: #3d3d3d;
        }
        .is-active {
          color: #007dff;
          background: #d9e8ff;
        }
        .second_link {
          .el-anchor__link {
            font-size: 14px;
            font-weight: 400;
            color: #4e5969;
            background: #f2f3f5;
          }
          .is-active {
            color: #007dff;
            background: #d9e8ff;
          }
        }
      }
    }
    .table_list {
      height: 100%;
      overflow: auto;
      box-sizing: border-box;
      background: #f5f7fa;
      .row_img {
        display: block;
        width: 80px;
        height: 80px;
        margin: 0 auto;
        border-radius: 4px;
      }
      .space {
        padding: 20px;
        margin-bottom: 20px;
        background: white;
        .title {
          display: flex;
          justify-content: space-between;
          .title_left {
            display: flex;
            font-size: 18px;
            color: #3d3d3d;
            align-items: end;
            .name {
              font-weight: 700;
            }
            .zone {
              font-size: 14px;
              color: #4e5969;
              line-height: 18px;
              .high_light {
                color: #ff3333;
              }
            }
          }
          .action {
            display: flex;
            color: #007dff;
            gap: 20px;
            .split_line {
              border-left: 1px solid #e1e6ed;
              margin: 3px 0;
            }
            .material,
            .quota {
              display: flex;
              align-items: center;
              gap: 10px;
            }
          }
        }
        .table {
          margin: 20px 0;
          border: 1px solid #e1e6ed;
          .table_head {
            background: #f2f6fc;
          }
        }
        .memo {
          display: grid;
          grid-template-columns: 60px 1fr;
          align-items: center;
          gap: 10px;
          color: #4e5969;
          .table_remark {
            border: 1px solid #e1e6ed;
            padding: 10px 18px;
          }
        }
        .tax {
          display: flex;
          gap: 20px;
          margin-bottom: 30px;
          .tax_box {
            width: 270px;
            .tax_title {
              display: flex;
              align-items: center;
              margin-bottom: 20px;
              font-size: 18px;
              font-weight: 700;
              color: #3d3d3d;
              .tip {
                margin-right: 10px;
              }
            }
            .tax_input {
              display: flex;
              gap: 10px;
              align-items: center;
            }
          }
        }
      }
      .affix {
        .affix_content {
          box-sizing: border-box;
          display: grid;
          grid-template-columns: 100%;
          grid-template-rows: 64px 68px;
          background: white;
          box-shadow: 0px -5px 10px 0px rgba(66, 78, 102, 0.15);
          .transaction {
            padding: 10px 20px;
            line-height: 24px;
            border-bottom: 1px solid #c2d4e8;
            .amount {
              font-weight: 700;
              color: #606266;
              .amount_num {
                color: #3d3d3d;
              }
            }
            .memo {
              font-size: 12px;
              color: #86909c;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
              width: calc(100% - 40px);
            }
          }
          .total {
            display: flex;
            align-items: center;
            padding: 20px;
            justify-content: space-between;
            font-size: 16px;
            .total_text {
              color: #606266;
            }
            .total_num {
              color: #ff3333;
            }
            .total_brackets {
              font-size: 14px;
              color: #86909c;
            }
            .total_detail {
              font-size: 12px;
              color: #86909c;
            }
          }
        }
      }
    }
  }
  .el-input {
    border: 1px solid #dcdfe6;
  }
  .el-input__wrapper {
    background: white;
  }
}
.quota_btn {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 10px 0px;
  background: #ffffff;
  box-shadow: 0px -3px 10px 0px rgba(4, 24, 48, 0.1);
  // border-radius: 0px 0px 0px 10px;
}
</style>
